<template>
  <div class="app-container">
    <h3 class="title">平台抽佣提现管理</h3>
    <div v-if="setPermissionBtn('/platformCommission/record/query/page', searchBtn)" class="inputBox">
      <el-input v-model="search.recordSn" class="input" placeholder="请输入单号查询" />
      <el-input v-model="search.createName" class="input" placeholder="请输入申请人姓名查询" />
      <!-- <el-input v-model="search.applyPhone" class="input" placeholder="请输入申请人手机号查询" /> -->
      <el-date-picker
        v-model="search.startTime"
        class="startDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-select v-model="search.status" class="input" placeholder="请选择提现状态">
        <el-option label="全部" value="" />
        <el-option label="待审核" value="0" />
        <el-option label="待放款" value="1" />
        <el-option label="已放款" value="2" />
        <el-option label="已驳回" value="3" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <template slot="empty">
        <div class="noData">暂无数据</div>
      </template>
      <el-table-column align="center" label="单号" width="100">
        <template slot-scope="scope">
          {{ scope.row.recordSn }}
        </template>
      </el-table-column>
      <el-table-column label="申请人" width="70">
        <template slot-scope="scope">
          {{ scope.row.createName }}
        </template>
      </el-table-column>
      <el-table-column label="提现金额">
        <template slot-scope="scope">
          {{ scope.row.amount }} 元
        </template>
      </el-table-column>
      <!-- <el-table-column label="申请人手机号" width="110">
        <template slot-scope="scope">
          {{ scope.row.applyPhone }}
        </template>
      </el-table-column> -->
      <el-table-column label="申请时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.createTime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="提现账户名称">
        <template slot-scope="scope">
          {{ scope.row.bankInfo }}
        </template>
      </el-table-column>
      <el-table-column label="提现账号" width="110">
        <template slot-scope="scope">
          {{ scope.row.platformAccount | hideBankCard }}
        </template>
      </el-table-column>
      <el-table-column label="收款人" width="80">
        <template slot-scope="scope">
          {{ scope.row.platformName }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="70">
        <template slot-scope="scope">
          <p>{{ scope.row.status|typeStr }}</p>
        </template>
      </el-table-column>
      <el-table-column label="提现来源">
        <template slot-scope="scope">
          {{ '平台抽佣' }}
          <!-- {{ scope.row.cashType | cashTypeStr }} -->
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="330">
        <template slot-scope="scope">
          <!-- v-show="permissionShow && permissionBoolean('详情')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/query', scope.row)"
            v-show="scope.row.status==0 || scope.row.status==1 || scope.row.status==2 || scope.row.status==3"
            value="详情"
            size="mini"
            type="warning"
            @click="detail(scope.$index)">{{ scope.row.btnName }}</el-button>
          <!-- v-show="permissionShow && permissionBoolean('备注')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/remark/query/page', scope.row)"
            v-show="scope.row.status==0 || scope.row.status==1"
            size="mini"
            value="备注"
            type="success"
            @click="changeRemarks(scope.row.id, scope.row.status)">{{ scope.row.btnName }}</el-button>
          <!-- v-show="permissionShow && permissionBoolean('查看备注')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/remark/query/page', scope.row)"
            v-show="scope.row.status==2 || scope.row.status==3"
            size="mini"
            value="查看备注"
            type="success"
            @click="checkRemark(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
          <!-- v-show="permissionShow && permissionBoolean('审核')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/review', scope.row)"
            v-show="scope.row.status==0"
            size="mini"
            value="审核"
            type="success"
            @click="waitCheck(scope.row.id, scope.row.platformCommissionId)">{{ scope.row.btnName }}</el-button>
          <!-- v-show="permissionShow && permissionBoolean('驳回')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/refused', scope.row)"
            v-show="scope.row.status==0"
            size="mini"
            value="驳回"
            type="danger"
            @click="rejectFn(scope.row.id, scope.row.platformCommissionId)">{{ scope.row.btnName }}</el-button>
          <!-- v-show="permissionShow && permissionBoolean('打款')" -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/loaned', scope.row)"
            v-show="scope.row.status == 1"
            size="mini"
            value="打款"
            type="success"
            @click="getCash(scope.row.id, scope.row.platformCommissionId)">{{ scope.row.btnName }}</el-button>
          <el-upload
            v-if="setPermissionBtn('/platformCommission/record/loanedVoucher', scope.row)"
            v-show="scope.row.status==2 && scope.row.imageUrl === null"
            ref="picUpload"
            :before-remove="beforeRemove"
            :before-upload="beforeAvatarUpload"
            :on-success="(file, filelist) => change( file, filelist, scope.row.id)"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :data="uploadData"
            :action="actionUrl"
            :with-credentials= "false"
            :model="imageUrl"
            value="上传打款凭证"
            multiple
            class="upload-demo fl"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
            <el-button size="mini" type="primary">{{ scope.row.btnName }}</el-button>
          </el-upload>
          <!-- <el-button
            v-show="scope.row.status==2"
            size="mini"
            type="success"
            @click="checkRemark(scope.row.id, scope.$index)">上传打款凭证</el-button> -->
          <el-button
            v-if="setPermissionBtn('/platformCommission/record/queryVoucher', scope.row)"
            v-show="scope.row.status==2 && scope.row.imageUrl !== null"
            size="mini"
            value="查看打款凭证"
            type="success"
            @click="checkVoucher(scope.row.id, scope.$index)">{{ scope.row.btnName }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <detail
      :detialvisible.sync="dialogTableVisible"
      :dialogdata.sync="list"
      :myindex.sync="detailIndex"
      :detail-mode="'platform'" />
    <remark :remark-list="remarkList" :remark-visible.sync="remarkVisible" :remark-index="remarkIndex" />
    <remarkPropt
      ref="remarke"
      :remark-propt-list="remarkProptList"
      :remark-propt-visible.sync="remarkProptVisible"
      :remark-propt-index="remarkProptIndex"
      :remark-type="'order'"
      @remarkText="remarkText" />
    <Voucher
      :showdialog.sync="voucherVisible"
      :voucher-data.sync="voucherData"
      :voucher-index.sync="voucherIndex"
      model="casher"
    />
  </div>
  <!-- voucherVisible, -->

</template>

<script>
import config from '@/utils/config';
import {
  upDateCashRecorde,
  checkRemark,
  getUserMessage,
  getPlatformCommissionList,
  findCashRemarksRecordList,
  reFusedPlatformCommissionRecord,
  loanedVoucher,
  queryVoucher,
  passPlatformCommissionRecord,
  loanedPlatformCommissionRecord,
  checkPlatremark,
  addPlatremark
} from '@/api/financial'
// import { getPlatformCommissionList } from '@/api/financial'
import Pagination from '@/components/Pagination'
import Voucher from '@/components/voucher'
import { Message } from 'element-ui'
import detail from '@/components/detail'
import remark from '@/components/remark'
import TableView from '@/components/TableView'
import remarkPropt from '@/components/remark/remarkPrompt'
import { getByteLength } from '@/utils/validate'
import { getLocalUid, setLocalUid, getLocalId, setLocalId, getLocalUserName, setLocalUserName } from '@/utils/uid'
import { getPermission } from '@/api/permission'
const inputValidatorNum = (v) => {
  if (getByteLength(v) > 600) {
    return false
  }
}

export default {
  components: { Pagination, detail, remark, remarkPropt, Voucher },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeStr(type) {
      const typesMap = {
        0: '待审核',
        1: '待放款',
        2: '已放款',
        3: '已驳回'
      }
      return typesMap[type]
    },
    cashTypeStr(type) {
      const cashMap = {
        1: '会员推广',
        2: '商品销售返佣'
      }
      return cashMap[type]
    }
  },
  data() {
    return {
      searchBtn: {},
      list: [],
      total: 0,
      listLoading: true,
      userName: '',
      listQuery: {
        pageNum: 1,
        pageSize: 10
      },
      search: {
        recordSn: '',
        createName: '',
        startTime: '',
        endTime: '',
        status: null
      },
      isShowDel: false,
      temp: {
        status: ''
      },
      dialogFormVisible: false,
      courseTypeId: null,
      course: {
        name: '',
        introduce: '',
        price: '',
        imgUrl: ''
      },
      fileList: [],
      imgSrc: '',
      actionUrl: config.BaseUrl + '/storage/create',
      imageUrl: '',
      isEdit: false,
      uploadData: {
        key: '',
        token: ''
      },
      dialogTableVisible: false,
      detailList: [],
      formLabelWidth: '120px',
      detailIndex: -1,
      remarkVisible: false,
      remarkList: [],
      remarkIndex: -1,
      remarkProptVisible: false,
      remarkProptList: [],
      remarkProptIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏
      permissionList: [], // 权限数据列表

      voucherVisible: false,
      voucherData: {},
      voucherIndex: -1
    }
  },
  computed: {
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  created() {
    this.fetchData()
    this.userName = getLocalUserName()
    // this.getPermissonFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    // 查看打款凭证
    checkVoucher(id, index) {
      this.voucherData = { id }
      this.voucherIndex = index
      this.voucherVisible = true
    },
    remarkText(value) {
      this.fetchData()
    },
    // 重置
    toReset() {
      this.search.recordSn = ''
      this.search.createName = ''
      this.search.startTime = ''
      this.search.endTime = ''
      this.search.status = ''
    },
    // 查询
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      this.listLoading = true
      //   this.search.startTime = new Date(this.search.startTime).getTime();
      //   this.search.endTime = new Date(this.search.endTime).getTime();
      const newData = this.$deleteNull(this.objectCon(this.listQuery, this.search))
      getPlatformCommissionList(newData).then(response => {
        console.log(response.data.list)
        this.list = response.data.list
        // this.list[2].status = 0
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 备注
    // changeRemarks(id, index) {
    //   this.remarkProptIndex = index
    //   // console.log('--->', id)
    //   let userData = ''
    //   // 先获取个人信息
    //   this.remarkProptVisible = true
    //   this.$refs.remarke.request(id)
    //   // console.log('==>'+JSON.stringify(this))
    //   upDateCashRecorde(id).then(res => {
    //     userData = res.data
    //     // console.log(userData)
    //     this.remarkProptList = userData
    //     this.remarkProptVisible = true
    //   })
    // },
    // 备注
    changeRemarks(id, status) {
      const userData = ''
      // 先获取个人信息
      //   userData = res.data.list
      //   const h = this.$createElement
      //   const remarkData = userData.remark
      //   console.log(userData)
      this.$prompt('请输入备注', '备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
        // message: remarkData.length ? h('div', null, [
        //   h('span', null, '记录人: ' + userData.name),
        //   h('span', { style: 'margin-left: 20px' }, this.$options.filters['formatDateMinute'](userData.createTime)),
        //   h('p', null, '备注: ' + userData.remark)
        // ]) : ''
      }).then(({ value }) => {
        this.listLoading = true
        const data = { recordId: id, remark: value, status } // status
        // 提交备注
        addPlatremark(data).then(res => {
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: '备注修改成功'
            });
            this.listLoading = false
          } else {
            Message.error(res.message + '-' + res.data)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    beforeRemove(file, fileList) {
      console.log('file:::', file)
      console.log('fileList:::', fileList)
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`).then(() => {
          // let index = fileList
          console.log()
        })
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG && !isGIF) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
      console.log('beforeAvatarUpload:', file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    change(file, fileList, id) {
      this.isUpload = true
      this.fileList = [];
      console.log('fileList:::', fileList)
      console.log('config.ImgUrl:::', config.ImgUrl)
      if (Number(fileList.response.code) === 200) {
        this.imageUrl = fileList.response.data.url
        console.log(id)
        loanedVoucher({ id, imageUrl: fileList.response.data.url }).then(res => {
          console.log(res)
          Message.success('图片上传成功')
          this.fetchData()
        })
        // let obj;
        // switch (type) {
        //   case 'coverImg': // 缩略图
        //     if (fileList.response.code === '200') {
        //       this.carouselList.imageUrl = fileList.response.data.url
        //     }
        //     break;
        //   case 'lbImg': // 轮播图
        //     obj = {
        //       posterImg: config.ImgUrl + fileList.response.data
        //     };
        //     this.isUpload = false
        //     this.imgsCurData.url = fileList.response.data.url
        //     // this.imgsCurData.curPath = fileList.url
        //     break;
        // }
      }
    },
    // 备注
    // changeRemarks(id) {
    //   let userData = ''
    //   // 先获取个人信息
    //   getPlatformCommissionList({ id }).then(res => {
    //     userData = res.data.list
    //     const h = this.$createElement
    //     const remarkData = userData.remark
    //     console.log(userData)
    //     this.$prompt('请输入备注', '备注', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       message: remarkData.length ? h('div', null, [
    //         h('span', null, '记录人: ' + userData.name),
    //         h('span', { style: 'margin-left: 20px' }, this.$options.filters['formatDateMinute'](userData.createTime)),
    //         h('p', null, '备注: ' + userData.remark)
    //       ]) : ''
    //     }).then(({ value }) => {
    //       const data = { id, remark: value }
    //       // 提交备注
    //       upDateCashRecorde(data).then(res => {
    //         if (res.code === '200') {
    //           this.fetchData();
    //           this.$message({
    //             type: 'success',
    //             message: '备注修改成功'
    //           });
    //         }
    //       })
    //     }).catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '取消输入'
    //       })
    //     })
    //   })
    // },

    // 查看备注
    checkRemark(id, index) {
      checkPlatremark({ recordId: id }).then(res => {
        console.log('查看备注', res)
        if (res.code === '200') {
          console.log(res)
          this.remarkList = res.data.list
          if (this.remarkList.length) {
            this.remarkVisible = true
            this.remarkIndex = index
          } else {
            this.$message('暂无备注');
          }
        }
      })
    },
    // 驳回
    rejectFn(id, platformCommissionId) {
      this.$prompt('请输入驳回理由', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: inputValidatorNum,
        inputErrorMessage: '最多输入200个字符'
      }).then(({ value }) => {
        this.listLoading = true
        const data = { id, platformCommissionId, refuseReason: value }
        // console.log(id, platformCommissionId)
        reFusedPlatformCommissionRecord(data).then(res => {
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: '已驳回!'
            });
            this.listLoading = false
          } else {
            Message.error(res.message + '-' + res.data)
            this.fetchData();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消驳回'
        })
      })
    },
    // 点击审核 - 待审核：点击审核按钮，审核通过后，状态变为“待放款”
    waitCheck(id, platformCommissionId) {
      this.$confirm('提款请求是否审核通过？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { id, platformCommissionId }
        passPlatformCommissionRecord(data).then(res => {
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: '审核成功!'
            });
          } else {
            Message.error(res.message + '-' + res.data)
            this.fetchData();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        })
      })
    },
    // 第一次加载 或 刷新页面
    fetchData() {
      this.listLoading = true
      const newData = this.$deleteNull(this.objectCon(this.listQuery, this.search))
      getPlatformCommissionList(newData).then(response => {
        console.log(response)
        this.list = response.data.list
        console.log(response.data.list)
        // this.list[0].bankCard = '1234567890123456'
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },
    // 打款
    getCash(id, platformCommissionId) {
      this.$confirm('是否确认打款?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { id, platformCommissionId }
        loanedPlatformCommissionRecord(data).then(res => {
          console.log(res)
          if (res.code === '200') {
            this.fetchData();
            this.$message({
              type: 'success',
              message: '打款成功!'
            });
          } else {
            Message.error(res.message + '-' + res.data)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消打款'
        })
      })
    },
    // 点击详情
    detail(index) {
      this.detailIndex = index
      this.dialogTableVisible = true
    },
    addCourse(courseTypeId) {
      this.$data.courseTypeId = courseTypeId
      this.$data.dialogFormVisible = true
    },
    getValue(value) {
      this.$data.temp.status = value
    },
    getEnable(value) {
      this.$data.course.isEnable = value
    },
    getChildren(value) {
      this.$data.course.courseList = value
    },
    addCourseType() {
      this.$router.push({
        path: 'add',
        query: { isEdit: false }
      })
    },
    editRow(pid) {
      const _this = this;
      const object = Object.assign({ isEdit: true }, _this.$data.list[pid])
      this.$router.push({
        path: 'add',
        query: object
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-icon-remove {
    margin-left: 10px;
  }
  .img_url {
    width: 110px;
    height: 110px;
  }
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 200px }
    .input:nth-of-type(2){ width: 180px }
    .input:nth-of-type(3){ width: 120px }
    .input:nth-of-type(4){ width: 120px }
    .startDate, .endDate{ width: 180px }
  }
  .upload-demo{
      display: inline-block;
      margin-left: 10px;
  }
</style>
